<!--
 * @Description: 富文本编辑器
 * @Author: 梁晓雨
 * @Date: 2025-02-08 19:15:06
-->
<template>
  <div>
    <div style="border: 1px solid #ccc; margin-top: 10px">
      <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" style="border-bottom: 1px solid #ccc" />
      <Editor :defaultConfig="editorConfig" :mode="mode" v-model="valueHtml" style="height: 400px; overflow-y: hidden"
        @onCreated="handleCreated" @onChange="handleChange" @onDestroyed="handleDestroyed" @onFocus="handleFocus"
        @onBlur="handleBlur" @customAlert="customAlert" @customPaste="customPaste" />
    </div>

  </div>
</template>

<script lang="ts" setup>
import '@wangeditor/editor/dist/css/style.css';
import { defineComponent, onBeforeUnmount, ref, shallowRef, onMounted } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { Editor as WangeditorInstance } from '@wangeditor/editor-for-vue/types/editor';
import { ElMessage } from 'element-plus';

const mode = ref('default')
// 编辑器实例
const editorRef = shallowRef<WangeditorInstance | null>(null);
// 内容HTML
const valueHtml = ref<string>('<p>hello</p>')
// 工具栏配置
const toolbarConfig = {}
// 编辑器配置
const editorConfig = { placeholder: '请输入内容' }

// 组件销毁时及时销毁编辑器！
onBeforeUnmount(
  () => {
    const editor = editorRef.value
    if (editor == null) return;
    editor.destroy();
  }
)
// 编辑器回调函数
const handleCreated = (editor: WangeditorInstance) => {
  console.log('created', editor);
  editorRef.value = editor; // 记录 editor 实例，重要！
};
const handleChange = (editor: WangeditorInstance) => {
  console.log('change:', editor.getHtml());
};
const handleDestroyed = (editor: WangeditorInstance) => {
  console.log('destroyed', editor);
};
const handleFocus = (editor: WangeditorInstance) => {
  console.log('focus', editor);
};
const handleBlur = (editor: WangeditorInstance) => {
  console.log('blur', editor);
};
const customAlert = (info: string, type: string) => {
  alert(`提示：${type} - ${info}`);
};
const customPaste = (editor: WangeditorInstance, event: ClipboardEvent, callback: (continuePaste: boolean) => void) => {
  console.log('ClipboardEvent 粘贴事件对象', event);
}

// 往父组件返回编辑器内容
const returnContent = () => {
  const editor = editorRef.value
  if(editor == null) return null
  return editor.getHtml()
}
/**
 * @description: 往父组件返回纯文本编辑器内容
 * @Author: 梁晓雨
 * @Date: 2025-03-04 22:02:52
 */
const returnContentText = () => {
  const editor = editorRef.value
  if(editor == null) return null
  return editor.getText()
}

/**
 * @description: 传入字符串修改编辑器的内容
 * @param: `text` 编辑器新内容 
 * @Author: 梁晓雨
 * @Date: 2025-03-04 22:04:51
 */
const contentChange = (text:string) => {
  const html = text.split(/\n/).map(line => `<p>${line}</p>`).join('\n')

  const editor = editorRef.value
  editor.setHtml(html)
}

defineExpose({
  returnContent,
  returnContentText,
  contentChange
}) 
</script>
<style lang="scss" scoped>

</style>